<template>
  <div class="data-collection-overview">
    <!-- 页面标题 -->
    <van-nav-bar title="数据采集" left-arrow @click-left="$router.back()" />

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <van-row gutter="12">
        <van-col span="12">
          <div class="stat-card success">
            <div class="stat-number">{{ overview.totalSuccess || 0 }}</div>
            <div class="stat-label">成功入库</div>
          </div>
        </van-col>
        <van-col span="12">
          <div class="stat-card error">
            <div class="stat-number">{{ overview.totalFailed || 0 }}</div>
            <div class="stat-label">失败记录</div>
          </div>
        </van-col>
      </van-row>
      
      <van-row gutter="12" style="margin-top: 12px;">
        <van-col span="12">
          <div class="stat-card info">
            <div class="stat-number">{{ formatAmount(overview.totalRmbAmount) }}</div>
            <div class="stat-label">人民币总额</div>
          </div>
        </van-col>
        <van-col span="12">
          <div class="stat-card warning">
            <div class="stat-number">{{ formatAmount(overview.totalUsdAmount) }}</div>
            <div class="stat-label">美元总额</div>
          </div>
        </van-col>
      </van-row>
    </div>

    <!-- 功能菜单 -->
    <van-cell-group inset title="数据采集功能">
      <van-cell
        title="入库统计"
        label="查看详细的入库统计数据和趋势分析"
        is-link
        @click="navigateTo('/storage-statistics')"
        icon="bar-chart-o"
      />
      <van-cell
        title="数据质量报告"
        label="查看数据质量检测报告"
        is-link
        @click="navigateTo('/data-quality-report')"
        icon="completed"
      />
      <van-cell
        title="采集任务监控"
        label="监控数据采集任务执行状态"
        is-link
        @click="navigateTo('/collection-monitor')"
        icon="eye-o"
      />
    </van-cell-group>

    <!-- 最近入库记录 -->
    <van-cell-group inset title="最近入库记录">
      <van-cell
        v-for="record in recentRecords"
        :key="record.id"
        :title="record.dataType"
        :label="record.clearanceDate"
      >
        <template #right-icon>
          <van-tag :type="record.storageStatus === 'SUCCESS' ? 'success' : 'danger'">
            {{ record.storageStatus === 'SUCCESS' ? '成功' : '失败' }}
          </van-tag>
        </template>
        <template #value>
          <div class="record-amount">
            {{ formatAmount(record.rmbAmount) }}
          </div>
        </template>
      </van-cell>
      
      <van-cell
        v-if="recentRecords.length === 0"
        title="暂无数据"
        label="还没有入库记录"
      />
      
      <van-cell
        v-if="recentRecords.length > 0"
        title="查看更多"
        is-link
        @click="navigateTo('/storage-statistics')"
      />
    </van-cell-group>

    <!-- 数据类型分布 -->
    <van-cell-group inset title="数据类型分布">
      <van-cell
        v-for="type in dataTypeStats"
        :key="type.dataType"
        :title="type.dataType"
        :value="`${type.count} 条记录`"
      >
        <template #label>
          <div class="type-progress">
            <van-progress
              :percentage="type.percentage"
              :color="getProgressColor(type.percentage)"
              :show-pivot="false"
            />
          </div>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 刷新按钮 -->
    <div class="refresh-section">
      <van-button
        type="primary"
        block
        round
        :loading="loading"
        @click="loadAllData"
      >
        刷新数据
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { storageStatisticsApi } from '@/api/datacollection'

const router = useRouter()
const loading = ref(false)
const overview = ref({})
const recentRecords = ref([])
const dataTypeStats = ref([])

const navigateTo = (path) => {
  router.push(path)
}

// 加载概览数据
const loadOverview = async () => {
  try {
    const response = await storageStatisticsApi.getOverview()
    overview.value = response.data || {}
  } catch (error) {
    console.error('加载概览数据失败:', error)
  }
}

// 加载最近记录
const loadRecentRecords = async () => {
  try {
    const response = await storageStatisticsApi.getPage({
      pageNo: 1,
      pageSize: 5
    })
    recentRecords.value = response.data?.records || []
  } catch (error) {
    console.error('加载最近记录失败:', error)
  }
}

// 加载数据类型统计
const loadDataTypeStats = async () => {
  try {
    const response = await storageStatisticsApi.getDataTypes()
    const dataTypes = response.data || []
    
    // 模拟统计数据（实际应该从后端获取）
    dataTypeStats.value = dataTypes.map((type, index) => ({
      dataType: type,
      count: Math.floor(Math.random() * 1000) + 100,
      percentage: Math.floor(Math.random() * 80) + 20
    }))
  } catch (error) {
    console.error('加载数据类型统计失败:', error)
  }
}

// 加载所有数据
const loadAllData = async () => {
  loading.value = true
  try {
    await Promise.all([
      loadOverview(),
      loadRecentRecords(),
      loadDataTypeStats()
    ])
    showToast('数据刷新成功')
  } catch (error) {
    showToast('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 格式化金额
const formatAmount = (amount) => {
  if (!amount) return '0'
  const num = Number(amount)
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toLocaleString()
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage >= 80) return '#07c160'
  if (percentage >= 60) return '#ff976a'
  if (percentage >= 40) return '#ffd21e'
  return '#ee0a24'
}

onMounted(() => {
  loadAllData()
})
</script>

<style scoped>
.data-collection-overview {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.stats-cards {
  padding: 16px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-card.success {
  border-left: 4px solid #07c160;
}

.stat-card.error {
  border-left: 4px solid #ee0a24;
}

.stat-card.info {
  border-left: 4px solid #1989fa;
}

.stat-card.warning {
  border-left: 4px solid #ff976a;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-card.success .stat-number {
  color: #07c160;
}

.stat-card.error .stat-number {
  color: #ee0a24;
}

.stat-card.info .stat-number {
  color: #1989fa;
}

.stat-card.warning .stat-number {
  color: #ff976a;
}

.stat-label {
  font-size: 12px;
  color: #969799;
}

.record-amount {
  font-size: 14px;
  color: #323233;
  font-weight: 500;
}

.type-progress {
  margin-top: 4px;
}

.refresh-section {
  padding: 16px;
  margin-top: 16px;
}
</style>
